package com.mianyang.zhangsan.plugin.quartz.util;

import com.alibaba.fastjson.JSONObject;
import com.mianyang.zhangsan.common.util.DateHelper;
import com.mianyang.zhangsan.model.entity.SecTask;
import com.mianyang.zhangsan.plugin.quartz.SecQuartzJob;
import com.mianyang.zhangsan.plugin.quartz.contant.QuartzConstant;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

/**
 * @author jiangjr
 * @date 2022-11-24
 */
@Slf4j
@Component
public class QuartzTaskFactory {

    public void addTask(Scheduler scheduler, SecTask task) {
        Trigger trigger;
        if (QuartzConstant.JOB_TYPE_ONCE == task.getTaskType()) {
            trigger = TriggerBuilder.newTrigger()
                    .withIdentity(QuartzUtils.getTriggerKey(task))
                    .startAt(DateHelper.parseSecond(task.getTaskTime()))
                    .build();
        } else {
            trigger = TriggerBuilder.newTrigger()
                    .withIdentity(QuartzUtils.getTriggerKey(task))
                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getTaskTime()))
                    .build();
        }
        JobDetail jobDetail = JobBuilder.newJob(SecQuartzJob.class)
                .withIdentity(QuartzUtils.getJobKey(task))
                .build();
        jobDetail.getJobDataMap().put(QuartzConstant.QUARTZ_TASK_KEY, JSONObject.toJSONString(task));
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.error("定时任务构建失败");
        }
    }

}
